const { tplReplace } = require('../utils');
// webpack 提供 专门为获取loader配置项
const { getOptions } = require('loader-utils');

function tplLoader(source) {  
  source = source.replace(/\s+/g, ''); // 去掉空格
  // console.log(source);
  // console.log(this);
  // this 上保存了很多很多数据

  const { log } = getOptions(this);

  // 打印路径
  const _log = log ?
              `console.log('compiled the file which is from ${ this.resourcePath }')`
              : '';

  return `
    export default (options) => {
      ${ tplReplace.toString() }
      ${ _log.toString() }
      return tplReplace('${ source }', options);
    }
  `
}

module.exports = tplLoader;

/**
 * const info = tpl({
  name: 'jackey',
  age: 18,
  career: 'Web Engineer',
  hobby: '看书、电影、旅游'
})
 */

// <div><h1>{{ name }}</h1><p>{{ age }}</p>   <p>{{ career }}</p><p>{{ hobby }}</p></div>

// 通过正则把对应的数据替换

// function tpl(options) {
//   function tplReplace(template, replaceObject) {
//     return template.replace(/\{\{(.*?)\}\}/g, (node, key) => {
//       return replaceObject[key];
//     })
//   }

//   return tplReplace(`${source}`, options);
// }
